;;; Guile-ZWave -- Guile talks with ZWave devices.
;;; Copyright © 2019, 2021 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of Guile-ZWave.
;;;
;;; Guile-ZWave is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Guile-ZWave is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-ZWave.  If not, see <http://www.gnu.org/licenses/>.


;; This is a simple example that watches notifications coming from ZWave
;; devices ("application command handler" messages).

(use-modules (zwave)
             (srfi srfi-71)
             (ice-9 match))

(define (run-alarm port)
  (let ((init (initialize-zwave-state port)))
    (write-serial-message (make-request (message-class get-initial-data))
                          port)
    (let loop ((state init))
      (match (select (list port) '() '())
        ((() () ())
         (loop state))
        (_
         (let* ((state1 (handle-response (pk 'msg (read-serial-message port))
                                         state))
                (notification state2 (pop-zwave-state-notification state1)))
           (pk 'nodes (zwave-state-nodes state2))
           (when notification
             (pk 'alarm notification))
           (loop state2)))))))

(run-alarm (open-zwave-serial-port (cadr (command-line))))
